package com.xms.file.api.controller;

import com.xms.core.data.Entity;
import com.xms.file.service.IAttachmentFinderService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.FileUtil;
import com.xms.utils.StringUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ClassUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * AttachmentController
 * </p>
 *
 * @author migo
 * @since 2021/9/26
 */
@RestController
@RequestMapping("/{org}/api/attachment")
public class AttachmentController extends ApiBaseController {
    private IAttachmentFinderService _attachmentFinderService;

    @Autowired
    public void AttachmentController(IAttachmentFinderService attachmentFinderService) {
        _attachmentFinderService = attachmentFinderService;
    }

    @ApiOperation("上传附件")
    @PostMapping(value = "upload", consumes = FileUploadBase.MULTIPART_FORM_DATA)
    public JsonResultObject upload(MultipartFile[] file, String name, String description) throws IOException {
        String folder = ClassUtils.getDefaultClassLoader().getResource("").getPath();// + uploadFolder;
        List<String> files = new ArrayList<>();
        for (MultipartFile f : file) {
            File ff = FileUtil.saveTo(f, folder);
            files.add(ff.getAbsolutePath());
        }
        return JOk(files);
    }

    @ApiOperation("下载附件")
    @GetMapping(value = "downloadfile", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downLoadFile(@RequestParam(value = "f", required = true) String filePath,
                             @RequestParam(required = false) String sid,
                             @RequestParam(required = false) Boolean preview) throws Exception {
        /*if (!sid.equalsIgnoreCase(_currentUser.getSessionId())) {
            return;
        }*/

        if (StringUtil.notEmpty(filePath)) {
            writeFileStream(filePath, "", "");
        }
    }

    @ApiOperation("下载附件")
    @GetMapping(value = "download/{id}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downLoad(@PathVariable UUID id,
                         @RequestParam(required = false) String sid,
                         @RequestParam(required = false) Boolean preview) throws Exception {
        /*if (!sid.equalsIgnoreCase(_currentUser.getSessionId())) {
            return;
        }*/
        Entity result = _attachmentFinderService.getById(id);
        if (CollectionUtil.isEmpty(result)) {
            return;
        }
        String filePath = result.getStringValue("cdnpath");
        String name = URLEncoder.encode(result.getStringValue("name"),"UTF-8");
        if (StringUtil.notEmpty(filePath)) {
            writeFileStream(filePath, result.getStringValue("mimetype"), name);
        } else if (StringUtil.notEmpty(result.getStringValue("body"))) {
            byte[] bt = Base64.getDecoder().decode(result.getStringValue("body").getBytes());
            File f = new File(filePath);
            OutputStream os = new FileOutputStream(f);
            StreamUtils.copy(bt, os);
            os.close();
            writeFileStream(f, result.getStringValue("mimetype"), name);
        }
    }
}
